// thyroidQuestionnaire.js
Page({
  data: {
    formData: {
      eyelidSign: '',
      rightEyeProtrusion: '',
      leftEyeProtrusion: '',
      eyeMovement: ''
    },
    imagePath: '',
    isSubmitting: false
  },

  onLoad: function() {
    // 页面加载时的逻辑
  },
  
  onShow: function() {
    // 检查登录状态
    const isLoggedIn = wx.getStorageSync('isLoggedIn');
    if (!isLoggedIn) {
      // 显示登录提示模态框
      wx.showModal({
        title: '请先登录',
        content: '完成登录后即可进行问卷评估',
        showCancel: true,
        cancelText: '暂不登录',
        confirmText: '立即登录',
        success: (res) => {
          if (res.confirm) {
            // 用户点击立即登录，跳转到授权登录页面
            wx.navigateTo({
              url: '/pages/authLogin/authLogin?redirect=questionnaire'
            });
          } else if (res.cancel) {
            // 用户点击暂不登录，返回首页
            wx.switchTab({
              url: '/pages/index/index'
            });
          }
        }
      });
    }
  },

  // 眼睑征输入变化
  onEyelidSignChange: function(e) {
    const formData = this.data.formData;
    formData.eyelidSign = e.detail.value;
    this.setData({
      formData: formData
    });
  },

  // 右眼突出度输入变化
  onRightEyeProtrusionChange: function(e) {
    const formData = this.data.formData;
    formData.rightEyeProtrusion = e.detail.value;
    this.setData({
      formData: formData
    });
  },

  // 左眼突出度输入变化
  onLeftEyeProtrusionChange: function(e) {
    const formData = this.data.formData;
    formData.leftEyeProtrusion = e.detail.value;
    this.setData({
      formData: formData
    });
  },

  // 眼球运动输入变化
  onEyeMovementChange: function(e) {
    const formData = this.data.formData;
    formData.eyeMovement = e.detail.value;
    this.setData({
      formData: formData
    });
  },

  // 选择图片
  chooseImage: function() {
    const that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        that.setData({
          imagePath: tempFilePath
        });
      }
    });
  },

  // 删除图片
  deleteImage: function() {
    this.setData({
      imagePath: ''
    });
  },

  // 表单验证
  validateForm: function() {
    const { eyelidSign, rightEyeProtrusion, leftEyeProtrusion, eyeMovement } = this.data.formData;
    const { imagePath } = this.data;

    if (!eyelidSign) {
      wx.showToast({ title: '请输入眼睑征情况', icon: 'none' });
      return false;
    }

    if (!rightEyeProtrusion || isNaN(Number(rightEyeProtrusion))) {
      wx.showToast({ title: '请输入有效的右眼突出度', icon: 'none' });
      return false;
    }

    if (!leftEyeProtrusion || isNaN(Number(leftEyeProtrusion))) {
      wx.showToast({ title: '请输入有效的左眼突出度', icon: 'none' });
      return false;
    }

    if (!eyeMovement) {
      wx.showToast({ title: '请输入眼球运动情况', icon: 'none' });
      return false;
    }

    if (!imagePath) {
      wx.showToast({ title: '请上传影像学检查报告', icon: 'none' });
      return false;
    }

    return true;
  },

  // 提交问卷评估
  submitForm: function() {
    // 验证表单
    if (!this.validateForm()) {
      return;
    }

    this.setData({
      isSubmitting: true
    });

    const { formData, imagePath } = this.data;
    
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    
    // 准备提交的表单数据
    const submitFormData = {
      eyelidSign: formData.eyelidSign,
      rightEyeProtrusion: formData.rightEyeProtrusion,
      leftEyeProtrusion: formData.leftEyeProtrusion,
      eyeMovement: formData.eyeMovement
    };
    
    // 如果用户已登录，添加用户ID
    if (userInfo && userInfo.id) {
      submitFormData.userId = userInfo.id;
    }

    // 调用后端API上传图片和问卷数据
    wx.uploadFile({
      url: 'http://localhost:5000/api/assessment/photo',
      filePath: imagePath,
      name: 'image',
      formData: submitFormData,
      success: (res) => {
        console.log('上传评估数据成功:', res.data);
        
        try {
          // 解析JSON响应
          const data = JSON.parse(res.data);
          if (data.success) {
            // 显示提交成功提示
            wx.showToast({
              title: '评估提交成功',
              icon: 'success',
              duration: 1500
            });
            
            // 跳转到报告页面
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/report/report'
              });
            }, 1500);
          } else {
            console.error('提交失败:', data.message);
            wx.showToast({
              title: data.message || '提交失败，请重试',
              icon: 'none'
            });
            this.setData({ isSubmitting: false });
          }
        } catch (e) {
          console.error('响应解析失败:', e);
          wx.showToast({
            title: '服务器响应错误',
            icon: 'none'
          });
          this.setData({ isSubmitting: false });
        }
      },
      fail: (err) => {
        console.error('上传评估数据失败:', err);
        wx.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        });
        this.setData({ isSubmitting: false });
      }
    });
  }
})